package com.chookss.home.inspection;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aliyun.svideo.common.utils.NetUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.ClockInGroupEntity;
import com.chookss.home.entity.InspectionEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.RoundCornerImageView;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.Nullable;
//巡检
public class InspectionHomeActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.tvInit)
    TextView tvInit;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    private MyAddressAdapter adapter;
    private List<InspectionEntity> list = new ArrayList<>();
    private String[] groupArray = null;
    private List<ClockInGroupEntity> groupEntities = new ArrayList<>();
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private String groupCode = "", groupName = "";
    private String locWd="", locJd="",locAddress="";//app定位经纬度
    private View emptyView;
    private TextView tvNone;//空布局;
    private InspectionEntity inspectionEntity = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_inspection_home);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        NavigationTools.saveUseRecord(this, "1", "36");
        commonTitleTxt.setText("项目名称");
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new MyAddressAdapter(R.layout.item_inspection, this, list);
        recyclerView.setAdapter(adapter);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        tvNone.setText("当前项目组暂无巡检地点");
        if (NetUtils.isGPSEnabled(this)) {
            showLoading();
            getPermissions();
            getGroupList();
        } else {
            showDialog();
        }
        smrRf.setEnableLoadMore(false);
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                if (Utils.isNull(groupCode)) {
                    MyToast.show("暂无项目组");
                    loadEnd();
                } else {
                    getAddresssList();
                }

            }
        });
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(tvNone.getText().toString().contains("定位")){
                    showLoading();
                    getPermissions();
                    getGroupList();
                }
            }
        });
    }
    private void showDialog() {
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(false)
                .asConfirm("提示", "定位服务未开启，请打开定位服务",
                        "取消", "去开启",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(intent);
                                finish();
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {
                                finish();
                            }
                        }, false)
                .show();
    }
    private void getPermissions() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            startLoc();
                        } else {
                            dismissLoading();
                            tvNone.setText("获取定位权限失败");
                            adapter.setEmptyView(emptyView);
                            tvInit.setVisibility(View.GONE);
                            MyToast.show("定位权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            dismissLoading();
                            tvNone.setText("获取定位权限失败");
                            adapter.setEmptyView(emptyView);
                            tvInit.setVisibility(View.GONE);
                            MyToast.show("被永久拒绝授权，请手动授予定位权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(InspectionHomeActivity.this, permissions);
                        } else {
                            dismissLoading();
                            tvNone.setText("获取定位权限失败");
                            adapter.setEmptyView(emptyView);
                            tvInit.setVisibility(View.GONE);
                            MyToast.show("获取定位权限失败");
                        }
                    }
                });
    }

    private String mainCd = "";

    private void getGroupList() {
        //项目组基本数据
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ClockInGroupEntity>>>() {
        }.getType(), null, Urls.selectMyItemGroupList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<ClockInGroupEntity>>() {
            @Override
            public void onSuccess(List<ClockInGroupEntity> data) {
                groupEntities.clear();
                groupCode = "";
                if (data != null && data.size() > 0) {
                    if (commonTitleTxt == null) {
                        return;
                    }

                    groupEntities.addAll(data);
                    groupArray = new String[groupEntities.size()];
                    for (int i = 0; i < groupEntities.size(); i++) {
                        if ("1".equals(groupEntities.get(i).getMainCd())) {
                            mainCd = groupEntities.get(i).getMainCd();
                            groupArray[i] = groupEntities.get(i).getGroupName() + "[常驻]";
                            groupCode = groupEntities.get(i).getGroupCode();
                            groupName = groupEntities.get(i).getGroupName();
                            commonTitleTxt.setText(groupEntities.get(i).getGroupName());
                        } else {
                            groupArray[i] = groupEntities.get(i).getGroupName();
                        }
                        if (i == groupEntities.size() - 1) {
                            if (Utils.isNull(mainCd)) {
                                groupCode = groupEntities.get(0).getGroupCode();
                                groupName = groupEntities.get(0).getGroupName();
                                commonTitleTxt.setText(groupEntities.get(0).getGroupName());
                            }
                        }
                    }
                }
                if (data.size() == 0) {
                    dismissLoading();
                    tvNone.setText("暂无项目组");
                    adapter.setEmptyView(emptyView);
                    tvInit.setVisibility(View.GONE);
                } else {
                    tvInit.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getAddresssList() {
        //巡检地理位置基本数据
        Map<String, String> map = new HashMap<>();
        map.put("jingdu", locJd);
        map.put("weidu", locWd);
        map.put("groupCode", groupCode);
        if (Utils.isNull(locJd) || Utils.isNull(locWd)) {
            return;
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<InspectionEntity>>>() {
        }.getType(), null, Urls.selectAddresssByGroupCode, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<InspectionEntity>>() {
            @Override
            public void onSuccess(List<InspectionEntity> data) {
                loadEnd();
                dismissLoading();
                if (commonTitleTxt == null) {
                    return;
                }
                list.clear();
                adapter.notifyDataSetChanged();
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyDataSetChanged();
                }
                if (list.size() == 0) {
                    adapter.setEmptyView(emptyView);
                    tvInit.setVisibility(View.GONE);
                } else {
                    tvInit.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void startLoc() {
        //声明LocationClient类
        try {
            if (mLocationClient == null) {
                LocationClient.setAgreePrivacy(true);
                mLocationClient = new LocationClient(getApplicationContext());
                LocationClientOption option = new LocationClientOption();
                mLocationClient.registerLocationListener(myListener);
                option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                option.setCoorType("bd09ll");
                option.setIsNeedAddress(true);
                option.setOpenGps(true);
                option.setScanSpan(1000);
                mLocationClient.setLocOption(option);
            }
            if (mLocationClient != null) {
                mLocationClient.start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
                if (msg.equals("RefreshInspectionList")) {
                    smrRf.autoRefresh();
                }
            }
        }
    }

    class MyAddressAdapter extends BaseQuickAdapter<InspectionEntity, BaseViewHolderEx> {
        private Context context;

        public MyAddressAdapter(int layoutResId, Context context, @Nullable List<InspectionEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, InspectionEntity item) {

            RoundCornerImageView ivBg = helper.getView(R.id.ivBg);
            TextView tvAddress = helper.getView(R.id.tvAddress);
            TextView tvNum = helper.getView(R.id.tvNum);
            TextView tvKm = helper.getView(R.id.tvKm);
            TextView tvCurrent = helper.getView(R.id.tvCurrent);
            int xunjianCd = Utils.changeNumber(item.getXunjianCd());
            boolean isClick = false;
            if (xunjianCd == 1) {
                isClick = true;
                if (helper.getItemPosition() == 0) {
                    tvCurrent.setVisibility(View.VISIBLE);
                    tvCurrent.setText("距离最近");
                } else {
                    tvCurrent.setVisibility(View.GONE);
                }
            } else if (xunjianCd == 2) {
                isClick = false;
                tvCurrent.setText("超出范围");
                tvCurrent.setVisibility(View.VISIBLE);
            } else {
                isClick = true;
                tvCurrent.setVisibility(View.VISIBLE);
            }
            tvAddress.setText(item.getAddressName());
            tvKm.setText("距离" + Utils.changeDistance(item.getDistance()));
            int num = Utils.changeNumber(item.getXunjianNumber());
            if (num == 0) {
                tvNum.setText("今日未巡检");
            } else {
                tvNum.setText("今日已巡检" + num + "次");
            }
            if (isClick) {
                tvAddress.setTextColor(Color.parseColor("#333333"));
                tvKm.setTextColor(Color.parseColor("#666666"));
                tvNum.setTextColor(Color.parseColor("#666666"));
                tvCurrent.setTextColor(getResources().getColor(R.color.main_color));
                tvCurrent.setBackgroundResource(R.drawable.inspection_red_bg);
            } else {
                tvAddress.setTextColor(Color.parseColor("#999999"));
                tvKm.setTextColor(Color.parseColor("#999999"));
                tvNum.setTextColor(Color.parseColor("#999999"));
                tvCurrent.setTextColor(Color.parseColor("#999999"));
                tvCurrent.setBackgroundResource(R.drawable.inspection_grey_bg);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (xunjianCd == 2) {
                        MyToast.show("超出巡检范围");
                        return;
                    }
                    startLoc();
                    requestCamera();
                    inspectionEntity = item;
                }
            });
        }
    }

    private void requestCamera() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            //选图片
                            openCamera();

                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(InspectionHomeActivity.this, denied, quick);
                    }
                });
    }
    private void openCamera() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofImage())
                .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        if(result!=null){
                            if(result.size()>0){
                                String url = "";
                                if (!Utils.isNull(result.get(0).getCompressPath())) {
                                    if (result.get(0).getCompressPath().contains("content://")) {
                                        Uri uri = Uri.parse(result.get(0).getCompressPath());
                                        url = PathUtil.getPath(InspectionHomeActivity.this, uri);
                                    } else {
                                        url = result.get(0).getCompressPath();
                                    }
                                } else {
                                    if (result.get(0).getPath().contains("content://")) {
                                        Uri uri = Uri.parse(result.get(0).getPath());
                                        url = PathUtil.getPath(InspectionHomeActivity.this, uri);
                                    } else {
                                        url = result.get(0).getPath();
                                    }
                                }
                                if(!Utils.isNull(locAddress)){
                                    inspectionEntity.setAddressAccuracyX(locJd);
                                    inspectionEntity.setAddressAccuracyY(locWd);
                                    inspectionEntity.setAddressName(locAddress);
                                }
                                Intent intent = new Intent(InspectionHomeActivity.this, InspectionPublishActivity.class);
                                intent.putExtra("data", inspectionEntity);
                                intent.putExtra("groupCode", groupCode);
                                intent.putExtra("groupName", groupName);
                                intent.putExtra("url", url);
                                startActivity(intent);
                            }
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });

    }


    @OnClick({R.id.common_title_back, R.id.topLl, R.id.common_right_iv_ll})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.topLl:
                if (groupArray == null) {
                    MyToast.show("无可选项目组，请联系管理员配置");
                    return;
                }
                new XPopup.Builder(InspectionHomeActivity.this)
                        .maxWidth(Utils.dip2px(InspectionHomeActivity.this, 260))
                        .maxHeight(Utils.dip2px(InspectionHomeActivity.this, 300))
                        .asCenterList("请选择项目组", groupArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        groupCode = groupEntities.get(position).getGroupCode();
                                        groupName = groupEntities.get(position).getGroupName();
                                        commonTitleTxt.setText(text.replace("[常驻]", ""));
                                        smrRf.autoRefresh();
                                    }
                                })
                        .show();
                break;
            case R.id.common_right_iv_ll:
                Intent intent = new Intent(this, InspectionGalleryListActivity.class);
                intent.putExtra("groupCode",groupCode);
                startActivity(intent);
                break;
        }
    }

    private int locationFlag = 0;
    private boolean firstLocation = true;

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                locationFlag++;
                if (!Utils.isNull(location.getAddrStr())) {
                    locWd = location.getLatitude() + "";
                    locJd = location.getLongitude() + "";
                    locAddress=location.getAddrStr();
                } else {

                    if (firstLocation) {
                        if (mLocationClient != null) {
                            firstLocation = false;
                            mLocationClient.start();
                        }
                    }
                }
                if (locationFlag >= 1 && !Utils.isNull(locWd) && !Utils.isNull(groupCode)) {
                    locationFlag = 0;
                    if (mLocationClient != null) {
                        dismissLoading();
                        mLocationClient.stop();
                    }
                    smrRf.autoRefresh();
                }
                if (locationFlag > 8) {
                    if (null != mLocationClient && mLocationClient.isStarted()) {
                        locationFlag = 0;
                        if (mLocationClient != null) {
                            dismissLoading();
                            mLocationClient.stop();
                        }
                    }
                }
            }else {
                if (firstLocation) {
                    if (mLocationClient != null) {
                        firstLocation = false;
                        mLocationClient.start();
                    }
                }
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
    }
}
